package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.model.vo.MemberResponseVo;
import com.atguigu.common.model.vo.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.intercepter.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();

        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //feign 异步 请求头缺失 ThreadLocal，异步时需要传递请求头
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            //远程查询用户收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            confirmVo.setAddress(address);
        }, threadPoolExecutor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            //远程查询购物车所有选中的购物项
            List<OrderItemVo> orderItemVos = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(orderItemVos);
        }, threadPoolExecutor).thenRunAsync(() -> {
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            //远程批量查询库存
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIdList = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            List<SkuHasStockVo> skusHasStock = wmsFeignService.getSkusHasStock(skuIdList);
            Map<Long, Boolean> stocks = skusHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            confirmVo.setStocks(stocks);
        }, threadPoolExecutor);

        //查询用户的积分信息
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegration(integration);

        //其他数据自动计算

        //防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(cartFuture, addressFuture).get();

        return confirmVo;
    }


    @Override
    @Transactional//本地事务，在分布式系统下只能控制自己的回滚，控制不了其他服务的回滚
    /**
     * 原子性 一起成功或失败
     * 一致性 业务的整体不受影响
     * 隔离性 各个事务互不干涉
     * 持久性 事务的操作完成后永远生效
     */
    /**
     * 事务的隔离级别
     * 1.读未提交 脏读
     * 2.读已提交 不可重复读
     * 3.可重复度 幻读        读取不会查询其他事务的操作，更新时会获取其他事务的变化     DEFAULT
     * 4.序列化
     */
    /**
     * 事务的传播行为
     * 1.REQUIRED：当前方法事务跟随上层方法的事务               DEFAULT
     * 2.REQUIRED_NEW：当前方法有自己的事务，和上层方法事务独立
     *
     */
    /**
     * 本地事务失效问题
     * 事务是由代理，切面完成的
     *
     * 事务方法直接调用或this调用，内部方法事务会失效【绕过代理】
     * 解决：
     * 1.引入aop模块，引入aspectj，开启aspectj动态代理功能，对外暴露代理对象，代理对象本类互调
     * 2.注入本类对象，代理调用
     * 数据库的连接和事务配置不一致
     *
     */
    @GlobalTransactional
    //分布式事务，最大原因，网络问题+分布式机器
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        OrderSubmitResponseVo response = new OrderSubmitResponseVo();
        response.setCode(0);
        //下单，去验令牌、创建订单、验价格、锁库存...
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        String orderToken = orderSubmitVo.getOrderToken();
        //1.验证令牌[令牌的对比和删除必须原子] 脚本返回 0:失败 或 1：成功
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);
        if (result == 1L) {
            //令牌验证通过
            //创建订单
            OrderCreateTo order = this.createOrder();
            //订单验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功
                //库存锁定-只要有异常回滚订单数据
                //订单号，所有订单项信息（skuId,skuName,num)
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                wareSkuLockVo.setLocks(order.getOrderItem().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList()));
                //远程锁库存
                //1. 库存锁定成功，返回超时，感知到库存服务的异常，创建订单回滚---->【库存锁定成功，订单没有创建】---->分布式事务
                //2. 库存锁定成功，订单创建异常--->库存服务已完成，无法回滚------->【库存锁定成功，订单没有正确创建】->分布式事务
                //事务在数据库的连接里边，不同的服务使用的不同的连接，无法多个服务实现同一个事务
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    //保存订单
                    this.saveOrder(order);
                    int i = 1 / 0;
                    response.setOrder(order.getOrder());
                    return response;
                } else {
                    //锁定失败
                    response.setMsg("库存锁定失败，请核对是否缺货");
                    response.setCode(3);
                    return response;
                }
            } else {
                //金额对比失败
                response.setMsg("订单价格发生变化，请确认后再次提交");
                response.setCode(2);
                return response;
            }
        } else {
            //令牌验证不通过
            response.setMsg("订单信息过期，请刷新再次提交");
            response.setCode(1);
            return response;
        }
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
//        if (orderToken != null && orderToken.equals(redisToken)) {
//            //令牌验证通过
//            return responseVo;
//        } else {
//            //令牌验证不通过
//            return responseVo;
//        }
    }


    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        orderService.save(order);
        List<OrderItemEntity> orderItem = orderCreateTo.getOrderItem();
        orderItemService.saveBatch(orderItem);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        String orderSn = IdWorker.getTimeId();

        //构建订单信息
        OrderEntity entity = this.buildOrder(orderSn);
        orderCreateTo.setOrder(entity);

        //构建订单项信息
        List<OrderItemEntity> orderItemEntityList = this.buildOrderItemList(orderSn);
        orderCreateTo.setOrderItem(orderItemEntityList);

        //计算价格相关
        this.computePrice(entity, orderItemEntityList);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> orderItemEntityList) {
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal coupon = BigDecimal.ZERO;
        BigDecimal integrationAmount = BigDecimal.ZERO;
        BigDecimal promotion = BigDecimal.ZERO;
        Integer growth = 0;
        Integer integration = 0;
        for (OrderItemEntity orderItemEntity : orderItemEntityList) {
            total = total.add(orderItemEntity.getRealAmount());
            coupon = coupon.add(orderItemEntity.getRealAmount());
            integrationAmount = integrationAmount.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            growth += orderItemEntity.getGiftGrowth();
            integration += orderItemEntity.getGiftIntegration();
        }
        entity.setTotalAmount(total);
        entity.setPayAmount(total.add(entity.getFreightAmount()));

        entity.setPromotionAmount(promotion);
        entity.setIntegrationAmount(integrationAmount);
        entity.setCouponAmount(coupon);
        entity.setGrowth(growth);
        entity.setIntegration(integration);
        //设置订单相关的状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
    }

    private List<OrderItemEntity> buildOrderItemList(String orderSn) {
        //2.获取到所有的订单项-最后确定每一项购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && !currentUserCartItems.isEmpty()) {
            return currentUserCartItems.stream().map(item -> this.buildOrderItem(orderSn, item)).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberResponseVo.getId());

        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();

        //获取收货地址信息
        R r = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {
        });

        //设置运费信息
        entity.setFreightAmount(fareVo.getFare());
        //设置收货信息
        entity.setReceiverName(fareVo.getAddress().getName());
        entity.setReceiverPhone(fareVo.getAddress().getPhone());
        entity.setReceiverProvince(fareVo.getAddress().getProvince());
        entity.setReceiverCity(fareVo.getAddress().getCity());
        entity.setReceiverRegion(fareVo.getAddress().getRegion());
        entity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        entity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        return entity;
    }

    private OrderItemEntity buildOrderItem(String orderSn, OrderItemVo item) {
        OrderItemEntity entity = new OrderItemEntity();
        //订单信息-订单号
        entity.setOrderSn(orderSn);
        //商品spu信息
        Long skuId = item.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        entity.setSpuId(spuInfoVo.getId());
        entity.setSpuBrand(spuInfoVo.getBrandId().toString());
        entity.setSpuName(spuInfoVo.getSpuName());
        entity.setCategoryId(spuInfoVo.getCatalogId());

        //商品sku信息
        entity.setSkuId(item.getSkuId());
        entity.setSkuName(item.getTitle());
        entity.setSkuPic(item.getImage());
        entity.setSkuPrice(item.getPrice());
        entity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(item.getSkuAttr(), ","));
        entity.setSkuQuantity(item.getCount());
        //优惠信息（不做）

        //积分信息
        entity.setGiftIntegration(item.getPrice().intValue());
        entity.setGiftGrowth(item.getPrice().intValue());

        //订单项的价格信息
        entity.setPromotionAmount(new BigDecimal("0"));
        entity.setCouponAmount(new BigDecimal("0"));
        entity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        entity.setRealAmount(entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString())));

        return entity;
    }

}